/**
 * @Copyright (C) 2015 by ywx.co.,ltd.All Rights Reserved.
 *  YWX CONFIDENTIAL AND TRADE SECRET
 */
package com.tanker.common.utils.microRental.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
* @Description:  生成签名和验证签名辅助类
 */
public class SignHelp {
	public static final String CHARSET = "utf-8";
	private static Logger log = LoggerFactory.getLogger(SignHelp.class);
	
	/**
	 * 生成签名类
	 * @Description: 
	 * @param parameter 请求的参数
	 * @param key 私钥
	 * @return 签名
	 */
	public static String generateSign(Map<String, String> parameter, String uri, String key){
		List<String> keys = new ArrayList<String>();
		keys.addAll(parameter.keySet());
		Collections.sort(keys);
		
		StringBuffer sb = new StringBuffer();
		
		for (String k : keys) {
			sb.append(k).append("=").append(parameter.get(k)).append("&");
        }
		
		sb.replace(sb.length()-1, sb.length(), "");
		
		String source = null;
		String encodeUri = null;
		try {
			encodeUri = URLEncoder.encode(uri, CHARSET);
			source = URLEncoder.encode(sb.toString(), CHARSET);
		} catch (UnsupportedEncodingException e) {
			log.error("encode parameter error", e);
		}
		
		
		byte[] b = HmacSha1Signature.sign(encodeUri + source, key);
		String serverSign = new String(Base64.encode(b));
		
		return serverSign;
	}
	
	
	/**
	 * @Description:  验证返回的数据
	 * @param data  返回的数据
	 * @param sign  返回的签名
	 * @param key  私钥 
	 * @return  返回的数据是否合法， true 合法， false不合法
	 */
	public static boolean validateSign(String data, String sign, String key){
		String source = null;
		try {
			source = URLEncoder.encode(data, CHARSET);
		} catch (UnsupportedEncodingException e) {
			log.error("encode parameter error", e);
		}
		
		byte[] b = HmacSha1Signature.sign(source, key);
		String clientSign = new String(Base64.encode(b));
		
		if(clientSign.equals(sign)){
			return true;
		}else{
			return false;
		}
	}
}
